package com.kkb.intercepter;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Author: 平川
 * @Description:
 * @Date Created in 2021-09-20 10:47
 * @Modified By:
 */
public class FileIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
                Map<String, MultipartFile> fileMap = mr.getFileMap();
                Iterator<String> iterator = fileMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    MultipartFile file = mr.getFile(key);
                    String of = file.getOriginalFilename();
                    String hz = of.substring(of.lastIndexOf("."));
                    //判断后缀是否合法
                    if (!hz.toLowerCase().equals(".png") || !hz.toLowerCase().equals(".jsp")) {
                        request.getRequestDispatcher("/test.jsp").forward(request, response);
                        flag = false;
                    }
                }
            }
        return flag;
    }
}
